<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { CreateElement } from 'vue'

@Component({
  name: 'CountdownButton'
})
export default class extends Vue {
  // countdown cycle, second
  @Prop({ type: Number, required: false, default: 60 })
  private duration!: number
  // countdown interval, second
  @Prop({ type: Number, required: false, default: 1 })
  private Interval!: number
  // button text
  @Prop({ type: String, required: false, default: 'start' })
  private buttonText!: string
  // button text when loading
  @Prop({ type: String, required: false, default: 'loading' })
  private loadingText!: string
  // button text when counting down
  @Prop({ type: String, required: false, default: '{value}' })
  private countingText!: string

  private loading: boolean = false
  private disabled: boolean = false
  private count: number = this.duration

  get text () {
    if (this.loading) {
      return this.loadingText
    } else if (this.disabled) {
      let length = this.duration.toString().length
      let count = (new Array(length).join('0') + this.count).slice(-length)
      return this.countingText.replace(/\{value\}/, count)
    } else {
      return this.buttonText
    }
  }

  private handleClick (): void {
    this.loading = true
    this.$emit('click')
  }
  private countdown (): void {
    this.disabled = true
    this.loading = false

    let timer = setInterval(() => {
      this.count -= this.Interval
      if (this.count <= 0) {
        clearInterval(timer)
        this.count = this.duration
        this.disabled = false
      }
    }, this.Interval * 1000)
  }
  private reset (): void {
    this.loading = false
    this.disabled = false
    this.count = this.duration
  }

  render (h: CreateElement) {
    return h(
      'el-button',
      {
        props: {
          ...this.$attrs,
          loading: this.loading,
          disabled: this.disabled
        },
        on: { click: this.handleClick }
      },
      this.text
    )
  }
}
</script>
